import Cookies from 'js-cookie'
import { CookieKey } from '@Components/assets/js/config'
import uuid from 'uuid/v4'
import { Base64 } from 'js-base64'
import DayJs from 'dayjs'
import localStore from '@Components/assets/js/utils/localStore'

// 判断是否站外图片
export const isExternalImg = url => {
  const reg = /(http|https):\/\//
  const path = url || ''
  return path.match(reg)
}

// 自动分摊金额
export const autoApportion = (total, count) => {
  let whileCount = count
  let lastTotal = total
  const totalRes = []
  while (whileCount > 1) {
    whileCount -= 1
    let res = Number((total / count).toFixed(2))
    lastTotal = Number((lastTotal - res).toFixed(2))
    totalRes.push(res)
  }
  totalRes.push(lastTotal)
  return totalRes
}

// 触发下载
export const downloadFile = (data, fileName, baseUrl) => {
  if (!data) return
  const url = baseUrl
    ? baseUrl + data
    : window.URL.createObjectURL(b64ToBlob(data))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
}

// 生成当天时间区间
export const generateTodayRange = () => [
  DayJs()
    .set('h', 0)
    .set('m', 0)
    .set('s', 0)
    .format('YYYY-MM-D HH:mm:ss'),
  DayJs()
    .set('h', 23)
    .set('m', 59)
    .set('s', 59)
    .format('YYYY-MM-D HH:mm:ss')
]

export const filterList = {
  kg(val) {
    val = Number(val)
    return `${!isNaN(val) ? val.toFixed(2) : 0}kg`
  },
  price(val) {
    val = Number(val)
    return `￥${!isNaN(val) ? val.toFixed(2) : 0}`
  },
  percent(val) {
    val = Number(val)
    return `${!isNaN(val) ? val.toFixed(2) : 0} %`
  }
}

// 深拷贝对象
export const deepCopy = obj => {
  return JSON.parse(JSON.stringify(obj))
}

// 计算table高度
/**
 * @param {Number} paneSize table所在的Splite分栏的高度
 * @param {Number} headHeight table所在的头部导航栏高度
 * @param {Array}  otherElClassList table所在的Splite分的栏其他同级元素的类名
 * @param {Number} appendValue 追加值，table加了margin-top or margin-bottom 的，请传入对应的值，确保页面统一
 * @param {Object} olBody table所在的载体
 * @return {Number} 表格高度
 */
export const generatorTableHeight = (
  { paneSize, headHeight = 0 },
  otherElClassList,
  appendValue = 0,
  olBody = null
) => {
  try {
    if (!otherElClassList) return 400
    let _otherElHeight = 0
    let body = olBody ? olBody : document.body
    otherElClassList.forEach(el => {
      const _el = body.querySelector(el)
      let marginTop =
        Number(window.getComputedStyle(_el).marginTop.replace('px', '')) || 0
      let marginBottom =
        Number(window.getComputedStyle(_el).marginBottom.replace('px', '')) || 0
      _otherElHeight += (_el ? _el.clientHeight : 0) + marginTop + marginBottom
    })
    if (olBody && body.style.height.replace('px', '') != body.clientHeight) {
      body = { clientHeight: body.style.height.replace('px', '') }
    }
    return body.clientHeight * (paneSize / 100) - headHeight - _otherElHeight - 5 - appendValue
  } catch (error) {
    return document.body.clientHeight - headHeight - 5 - appendValue
  }
}

// base64转blob
export const b64ToBlob = function (
  b64Data,
  contentType = 'application/octet-stream',
  sliceSize = 512
) {
  const byteCharacters = atob(b64Data)
  const byteArrays = []
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize)

    const byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

  const blob = new Blob(byteArrays, { type: contentType })
  return blob
}

// 生成唯一ID值
export const generateGuid = () => {
  return uuid().toString()
}

// 处理cookie的转换
export const handleCookie = function () {
  const data = Cookies.get(CookieKey)
  if (!data) throw new Error('cookie 为空')
  window.localStorage.setItem('USER_INFO', Base64.decode(data || {}))
}

// 数组求和
/**
 *
 * @param {Array} array
 * @returns {number}
 */
export const arraySum = array => {
  if (array.length === 0) return 0
  if (array.length === 1) {
    const sum = Number(array[0])
    return sum || 0
  }

  return array.reduce((preItem, item, currentIdx) => {
    let preNum = Number(preItem)
    let currentNum = Number(item)
    currentNum = isNaN(currentNum) ? 0 : currentNum

    if (currentIdx === 1) {
      preNum = isNaN(preNum) ? 0 : preNum
    }
    return preNum + currentNum
  })
}

// table合计
/**
 * @param {Array} columns table字段的信息
 * @param {Array} data table字段的数据
 * @param {Array} numCol table需要合计数字的字段
 * @param {Array} priceCol table需要合计数字(金额)的字段
 * @return {Array} table的合计
 */
export const tableSummary = function ({
  columns,
  data,
  numCol = [],
  priceCol = []
}) {
  return columns.map((col, colIdx) => {
    const isNumCol = numCol.includes(col.property)
    const isPriceCol = priceCol.includes(col.property)
    let sum = 0
    if (colIdx === 0) {
      return '合计'
    }

    if (isPriceCol || isNumCol) {
      sum = arraySum(data.map(i => i[col.property]))
    }

    switch (true) {
      case isPriceCol:
        return `￥${sum.toFixed(2)}`
      case isNumCol:
        return `${sum.toFixed()}`
    }
    return ''
  })
}

// 创建自增单号 * 结尾必须是数字
export const createAutoIncrementNo = (no = '') => {
  const p = /([0-9]+)$/
  const noSplit = no.split(p, 2)
  if (noSplit.length === 2) {
    return noSplit[0] + (parseInt(noSplit[1]) + 1)
  }
  return no
}

//创建枚举
export function newEnum(...arg) {
  const result = {}
  arg.forEach((e, index) => {
    result[(result[e] = index)] = e
  })
  return result
}
